import 'dart:io';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:convert';

import 'ObjectUtil.dart';


class CompressImageManager {

  /// 删除本地图片
  static void deleteImage(String imagePath) {
    File file = File(imagePath);
    if (file.existsSync()) {
      file.deleteSync();
      print('图片已删除：$imagePath');
    } else {
      print('图片不存在：$imagePath');
    }
  }

  /// 压缩图片
  static Future<String> compressImage(String imagePath,String targetPath) async {

    CompressFormat imageFormat = CompressFormat.jpeg;
    bool isCompress = false;
    if(imagePath.endsWith(".png") || imagePath.endsWith(".PNG")){
      imageFormat = CompressFormat.png;
    }else if(imagePath.endsWith(".jpeg") ||imagePath.endsWith(".JPEG") ||imagePath.endsWith(".JPG") || imagePath.endsWith(".jpg") ){
      imageFormat = CompressFormat.jpeg;
    }else if(imagePath.endsWith('.heic') || imagePath.endsWith('.HEIC')){
      isCompress = true;
      // imageFormat = CompressFormat.heic;
    }else if(imagePath.endsWith(".webp") || imagePath.endsWith(".WEBP")){
      isCompress = true;
      // imageFormat = CompressFormat.webp;
    }else{
      return imagePath;
    }





    double size = await CompressImageManager.getImageSizeInKB(imagePath);
    debugPrint("图片大小为 $size");
    if(size < 600 && isCompress == false){
      //600KB一下不压缩
      debugPrint("不压缩");
      return imagePath;
    }
    int compressRate = 70;
    if(size > 3000){
      compressRate = 50;
    }
    debugPrint("compressImageImagePath = $imagePath");
    debugPrint("compressImageTargetPath = $targetPath");
    var compressedImage = await FlutterImageCompress.compressAndGetFile(
        imagePath, targetPath,
        quality: compressRate,
        format: imageFormat
    );

    debugPrint("compressedImage = ${compressedImage?.path?? imagePath}");
    return compressedImage?.path?? imagePath;
  }

  static Future<double> getImageSizeInKB(String imagePath) async {
    if(ObjectUtil.isEmpty(imagePath)){
      return 0;
    }
    File file = File(imagePath);
    int fileSizeBytes = await file.length();
    double fileSizeKB = fileSizeBytes / 1024;
    double size =  roundDoubleToTwoDecimalPlaces(fileSizeKB);
    debugPrint("图片大小为 $size");
    return size;
  }
  static double roundDoubleToTwoDecimalPlaces(double numValue) {
    num roundedValue = (numValue * 100).round() / 100;
    return roundedValue.toDouble();
  }

  static Future<String> _getCacheDirectoryPath() async {
    final directory = await getTemporaryDirectory();
    return directory.path;
  }


  static Future<String> getCompressImagePath(String imageName) async {
    String path = await _getCacheDirectoryPath();
    String dir = "${path}/compressFolder";
    bool folderExists = await Directory(dir).exists();
    if (folderExists) {
    } else {
      await Directory(dir).create(recursive: true);
      debugPrint("DirectoryPath-result = $dir");
    }
    imageName = changeTargetImageName(imageName);
    return "${path}/compressFolder/${imageName}";
  }


  /// 如果图片格式为 heic 或者 webp 转化为jpeg；
  static String changeTargetImageName(String imageName){
    String lowerCaseString = imageName.toLowerCase();
    if(lowerCaseString.endsWith(".heic")){
      String replacedText = lowerCaseString.replaceAll(".heic", ".jpeg");
      return replacedText;
    }
    if(lowerCaseString.endsWith(".webp")){
      String replacedText = lowerCaseString.replaceAll(".webp", ".jpeg");
      return replacedText;
    }
    return imageName;
  }

  static Future<String> getWatermarkImagePath(String imageName) async {
    String path = await _getCacheDirectoryPath();
    String dir = "${path}/watermarkImage";
    bool folderExists = await Directory(dir).exists();
    if (folderExists) {
    } else {
      await Directory(dir).create(recursive: true);
      debugPrint("watermarkImage-result = $dir");
    }
    imageName = changeTargetImageName(imageName);
    return "${path}/watermarkImage/${imageName}";
  }

  // 生成随机图片路径
  static String generateRandomImagePath(String directory, String extension) {
    final random = Random();
    final timestamp = DateTime.now().millisecondsSinceEpoch;
    final randomNumber = random.nextInt(9999) + 1000;
    final randomName = 'image_${timestamp}_$randomNumber';
    return '$directory/$randomName$extension';
  }
}

